# listings/views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import login  # 用于注册后自动登录
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.db.models import Count
# from django.contrib.auth.forms import UserCreationForm # Django 内置的简单注册表单
from .forms import CustomUserCreationForm, SkillForm, NeedForm
from .models import CustomUser, Skill, Need  # 导入模型，用于首页展示


def home_view(request):
    # 获取最新的技能和需求
    latest_skills = Skill.objects.filter(is_active=True).order_by('-created_at')[:5]
    latest_needs = Need.objects.filter(is_active=True).order_by('-created_at')[:5]
    
    # 获取统计数据
    context = {
        'latest_skills': latest_skills,
        'latest_needs': latest_needs,
        'skill_count': Skill.objects.filter(is_active=True).count(),
        'need_count': Need.objects.filter(is_active=True).count(),
        'user_count': CustomUser.objects.count(),
    }
    return render(request, 'listings/home.html', context)


def register_view(request):
    if request.method == 'POST':
        form = CustomUserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            messages.success(request, '注册成功！欢迎来到平台。')
            return redirect('listings:home')
    else:
        form = CustomUserCreationForm()
    return render(request, 'registration/register.html', {'form': form})


@login_required
def profile_view(request):
    user_skills = Skill.objects.filter(provider=request.user)
    user_needs = Need.objects.filter(requester=request.user)
    context = {
        'user': request.user,
        'skills': user_skills,
        'needs': user_needs,
    }
    return render(request, 'listings/profile.html', context)


# 技能相关视图
def skill_list(request):
    skills = Skill.objects.filter(is_active=True)
    
    # 添加筛选条件
    category = request.GET.get('category')
    reward_type = request.GET.get('reward_type')
    search_query = request.GET.get('q')
    
    if category:
        skills = skills.filter(category=category)
    if reward_type:
        skills = skills.filter(reward_type=reward_type)
    if search_query:
        skills = skills.filter(title__icontains=search_query) | \
                skills.filter(description__icontains=search_query) | \
                skills.filter(tags__icontains=search_query)
    
    # 排序
    sort_by = request.GET.get('sort', '-created_at')
    skills = skills.order_by(sort_by)
    
    context = {
        'skills': skills,
        'categories': dict(Skill.CATEGORY_CHOICES),
        'reward_types': dict(Skill.REWARD_TYPE_CHOICES),
        'current_category': category,
        'current_reward_type': reward_type,
        'current_search': search_query,
        'current_sort': sort_by,
    }
    return render(request, 'listings/skill_list.html', context)

@login_required
def skill_create(request):
    if request.method == 'POST':
        form = SkillForm(request.POST)
        if form.is_valid():
            skill = form.save(commit=False)
            skill.provider = request.user
            skill.save()
            messages.success(request, '技能发布成功！')
            return redirect('listings:skill_detail', pk=skill.pk)
    else:
        form = SkillForm()
    return render(request, 'listings/skill_form.html', {'form': form, 'title': '发布技能'})

def skill_detail(request, pk):
    skill = get_object_or_404(Skill, pk=pk)
    context = {
        'skill': skill,
    }
    return render(request, 'listings/skill_detail.html', context)

@login_required
def skill_edit(request, pk):
    skill = get_object_or_404(Skill, pk=pk, provider=request.user)
    if request.method == 'POST':
        form = SkillForm(request.POST, instance=skill)
        if form.is_valid():
            form.save()
            messages.success(request, '技能更新成功！')
            return redirect('listings:skill_detail', pk=skill.pk)
    else:
        form = SkillForm(instance=skill)
    return render(request, 'listings/skill_form.html', {'form': form, 'title': '编辑技能'})

# 需求相关视图
def need_list(request):
    needs = Need.objects.filter(is_active=True)
    
    # 添加筛选条件
    category = request.GET.get('category')
    reward_type = request.GET.get('reward_type')
    search_query = request.GET.get('q')
    
    if category:
        needs = needs.filter(category=category)
    if reward_type:
        needs = needs.filter(reward_type=reward_type)
    if search_query:
        needs = needs.filter(title__icontains=search_query) | \
               needs.filter(description__icontains=search_query) | \
               needs.filter(tags__icontains=search_query)
    
    # 排序
    sort_by = request.GET.get('sort', '-created_at')
    needs = needs.order_by(sort_by)
    
    context = {
        'needs': needs,
        'categories': dict(Need.NEED_CATEGORY_CHOICES),
        'reward_types': dict(Need.REWARD_TYPE_CHOICES),
        'current_category': category,
        'current_reward_type': reward_type,
        'current_search': search_query,
        'current_sort': sort_by,
    }
    return render(request, 'listings/need_list.html', context)

@login_required
def need_create(request):
    if request.method == 'POST':
        form = NeedForm(request.POST)
        if form.is_valid():
            need = form.save(commit=False)
            need.requester = request.user
            need.save()
            messages.success(request, '需求发布成功！')
            return redirect('listings:need_detail', pk=need.pk)
    else:
        form = NeedForm()
    return render(request, 'listings/need_form.html', {'form': form, 'title': '发布需求'})

def need_detail(request, pk):
    need = get_object_or_404(Need, pk=pk)
    context = {
        'need': need,
    }
    return render(request, 'listings/need_detail.html', context)

@login_required
def need_edit(request, pk):
    need = get_object_or_404(Need, pk=pk, requester=request.user)
    if request.method == 'POST':
        form = NeedForm(request.POST, instance=need)
        if form.is_valid():
            form.save()
            messages.success(request, '需求更新成功！')
            return redirect('listings:need_detail', pk=need.pk)
    else:
        form = NeedForm(instance=need)
    return render(request, 'listings/need_form.html', {'form': form, 'title': '编辑需求'})

@login_required
def my_skills(request):
    skills = Skill.objects.filter(provider=request.user).order_by('-created_at')
    return render(request, 'listings/my_skills.html', {'skills': skills})

@login_required
def my_needs(request):
    needs = Need.objects.filter(requester=request.user).order_by('-created_at')
    return render(request, 'listings/my_needs.html', {'needs': needs})

@login_required
def contact_provider(request, pk):
    skill = get_object_or_404(Skill, pk=pk)
    if request.method == 'POST':
        message = request.POST.get('message')
        if message:
            # 这里可以添加发送消息的逻辑，比如创建一个Message模型
            messages.success(request, f'已成功向{skill.provider.username}发送消息')
        else:
            messages.error(request, '消息内容不能为空')
    return redirect('listings:skill_detail', pk=pk)

@login_required
def contact_requester(request, pk):
    need = get_object_or_404(Need, pk=pk)
    if request.method == 'POST':
        message = request.POST.get('message')
        if message:
            # 这里可以添加发送消息的逻辑，比如创建一个Message模型
            messages.success(request, f'已成功向{need.requester.username}发送消息')
        else:
            messages.error(request, '消息内容不能为空')
    return redirect('listings:need_detail', pk=pk)

# Django 内置的登录和注销视图会处理大部分逻辑，
# 我们只需要提供模板即可（或者使用 Django 默认的）。
# 如果需要自定义登录后的跳转等行为，可以覆盖这些视图。
from django.shortcuts import render

# Create your views here.
